#!/usr/bin/env python
# -*-coding:UTF-8-*-
# Author: chenzuoqing@126.com
# Create: 2018/8/14 17:40
# File  : filter.py

"""

"""

import django_filters
from django.db.models import Q
from sqlaudit.models import DatabaseConfig, AuditSQL


class DatabaseFilter(django_filters.FilterSet):
    name = django_filters.CharFilter(name='name', lookup_expr='icontains')
    env = django_filters.CharFilter(name='env', lookup_expr='exact')
    search = django_filters.CharFilter(method='multi_filter')

    @staticmethod
    def multi_filter(queryset, name, value):
        return queryset.filter(Q(name__icontains=value) | Q(host__icontains=value) |
                               Q(port__icontains=value) | Q(user__icontains=value) |
                               Q(remark__icontains=value) | Q(env__icontains=value))

    class Meta:
        model = DatabaseConfig
        fields = ['name', 'env']


class AuditSQLFilter(django_filters.FilterSet):
    id = django_filters.CharFilter(name='id', lookup_expr='exact')
    search = django_filters.CharFilter(method='multi_filter')
    env = django_filters.CharFilter(name='env', lookup_expr='exact')
    user = django_filters.CharFilter(method='id_filter')

    @staticmethod
    def multi_filter(queryset, name, value):
        return queryset.filter(Q(id__exact=value) |
                               Q(env__icontains=value) |
                               Q(remark__icontains=value) |
                               Q(sql_content__icontains=value) |
                               Q(commiter__username__icontains=value) |
                               Q(commiter__name__icontains=value) |
                               Q(treater__username__icontains=value) |
                               Q(treater__name__icontains=value)
                               )

    @staticmethod
    def id_filter(queryset, name, value):
        return queryset.filter(Q(commiter__id__exact=value) | Q(treater__id__exact=value))

    class Meta:
        model = AuditSQL
        fields = ['sql_content', 'env', 'id']
